<template>
    <div>
        <el-dialog :visible.sync="dialogVisible" :title="logType == 'create' ? '新增活动' : '编辑活动'" width="60%">
            <el-form ref="form" :model="formData" :rules="rules" label-width="140px" size="mini">
                <el-form-item label="活动标题:" prop="name">
                    <el-input style="width: 50%;" show-word-limit maxlength="50" v-model="formData.name"
                        placeholder="请输入标题" />
                </el-form-item>

                <el-form-item label="活动时间:" prop="time">
                    <el-date-picker style="width: 50%;" v-model="formData.time" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
                        format="yyyy年MM月dd日 HH时mm分ss秒">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="活动类型:" prop="type">
                    <el-radio-group v-model="formData.type">
                        <el-radio v-for="(v, idx) in typeList" :key="idx" :label="v.value">{{ v.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="是否启用阶梯奖励:" v-if="formData.type == 'brokerage'" prop="ladderEnabled">
                    <el-switch v-model="formData.ladderEnabled"></el-switch>
                </el-form-item>

                <div v-if="formData.ladderEnabled">
                    <el-form-item prop="ladderMin">
                        最小人数 <el-input style="width: 100px;" v-model="formData.ladderMin"></el-input> 人
                    </el-form-item>
                    <el-form-item prop="ladderMan">
                        最大人数 <el-input style="width: 100px;" v-model="formData.ladderMan"></el-input> 人
                    </el-form-item>
                    <div>
                        <el-form-item label="阶梯奖励类型:" prop="ladderRewardType">
                            <el-radio-group v-model="formData.ladderRewardType">
                                <el-radio v-for="(v, idx) in sendTypeList" :key="idx" :label="v.value">{{ v.label
                                }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <div>
                            <el-form-item v-if="formData.ladderRewardType === 1" prop="ladderRewardNum">
                                可查次数 <el-input style="width: 100px;" v-model="formData.ladderRewardNum"></el-input> 次
                            </el-form-item>
                            <el-form-item v-if="formData.ladderRewardType === 2" prop="ladderRewardPrice">
                                奖励金额 <el-input style="width: 100px;" v-model="formData.ladderRewardPrice"></el-input> 元
                            </el-form-item>
                        </div>
                    </div>
                </div>

                <div v-if="formData.type === 'register'">
                    <el-form-item label="发送类型:" prop="rewardType">
                        <el-radio-group v-model="formData.rewardType">
                            <el-radio v-for="(v, idx) in sendTypeList" :key="idx" :label="v.value">{{
                                v.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <div>
                        <el-form-item v-if="formData.rewardType === 1" prop="rewardNum">
                            可查次数 <el-input style="width: 100px;" v-model="formData.rewardNum"></el-input> 次
                        </el-form-item>
                        <el-form-item v-if="formData.rewardType === 2" prop="rewardPrice">
                            奖励金额 <el-input style="width: 100px;" v-model="formData.rewardPrice"></el-input> 元
                        </el-form-item>
                    </div>
                </div>

                <el-form-item label="奖励发放条件:" prop="giftConditionType">
                    <el-radio-group v-model="formData.giftConditionType">
                        <el-radio v-for="(v, idx) in tlList" :key="idx" :label="v.value">{{ v.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <div style="margin-top: 20px; display: flex; justify-content: space-between; padding:0 30px;"
                    v-if="formData.type !== 'register'">
                    <div style="font-size: 18px; font-weight: bold; color: #000;">条件设置</div>
                    <el-button type="text" @click="addRule()">添加条件</el-button>
                </div>

                <div v-if="formData.type !== 'register'">
                    <div v-for="(item, index) in formData.rules" :key="index"
                        style="border: 1px solid #eee; padding: 20px 0; margin: 20px 0; position: relative;">
                        <div style="text-align: right; padding-right: 20px; " v-if="index > 0">
                            <el-button style="" type="text" @click="formData.rules.splice(index, 1)">删除</el-button>
                        </div>
                        <el-form-item label="查询类型：" :prop="'rules.' + index + '.queryType'" :rules="rules.queryType">
                            <el-radio-group style="width: 1000px" v-model="item.queryType">
                                <el-radio v-for="(item, idx) in searchTypeList" :key="idx" :label="item.value">
                                    {{ item.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="查询条件：" :prop="'rules.' + index + '.queryConditionType'"
                            :rules="rules.queryConditionType">
                            <el-radio-group style="width: 1000px" v-model="item.queryConditionType">
                                <el-radio v-for="(item, idx) in queryConditionTypeList" :key="idx" :label="item.value">
                                    {{ item.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="奖励类型:" :prop="'rules.' + index + '.rewardType'" :rules="rules.rewardType">
                            <el-radio-group style="width: 1000px" v-model="item.rewardType">
                                <el-radio v-for="(item, idx) in sendTypeList" :key="idx" :label="item.value">
                                    {{ item.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <div>
                            <el-form-item v-if="item.rewardType === 1" :prop="'rules.' + index + '.rewardNum'"
                                :rules="rules.rewardNum">
                                可查次数 <el-input style="width: 100px;" v-model="item.rewardNum"></el-input> 次
                            </el-form-item>
                            <el-form-item v-if="item.rewardType === 2" :prop="'rules.' + index + '.rewardPrice'"
                                :rules="rules.rewardPrice">
                                奖励金额 <el-input style="width: 100px;" v-model="item.rewardPrice"></el-input> 元
                            </el-form-item>
                        </div>
                    </div>
                </div>

                <el-form-item label="活动奖励规则:" prop="description">
                    <Tinymce ref="tinymce" v-model="formData.description" :height="600" width="100%" />
                </el-form-item>
                <el-form-item label="活动背景图片:" prop="posterUrls">
                    <single-upload :border="'1px solid #ccc'" uploadType="2" @uploadSucces="uploadSucces"
                        v-model="formData.posterUrls">
                        <div class="uploadPic" v-if="!formData.posterUrls">
                            <i style="font-size: 40px; color: #ccc; font-weight: bold" class="el-icon-plus"></i>
                        </div>
                    </single-upload>
                </el-form-item>
                <el-form-item v-if="formData.type == 'query'" label="备注:" prop="note">
                    <el-input type="textarea" placeholder="请输入内容" maxlength="200" v-model="formData.note"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">保存</el-button>
                    <el-button @click="handleClose">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import SingleUpload from "@/components/Upload/uploadOne";
import { addActivity, updateActivity, activityInfo } from '@/api/activity'
export default {
    components: {
        Tinymce,
        SingleUpload
    },

    data() {
        // 自定义校验规则
        const validateNumber = (rule, value, callback) => {
            if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入数字'));
            } else if (!/^\d+$/.test(value)) {
                callback(new Error('请输入正整数'));
            } else {
                callback();
            }
        };

        const validateMoney = (rule, value, callback) => {
            if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入金额'));
            } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
                callback(new Error('请输入正确的金额格式，最多两位小数'));
            } else if (Number(value) <= 0) {
                callback(new Error('金额必须大于0'));
            } else {
                callback();
            }
        };

        const validateLadderRange = (rule, value, callback) => {
            if (this.formData.ladderEnabled) {
                const min = Number(this.formData.ladderMin);
                const max = Number(this.formData.ladderMan);
                if (min >= max) {
                    callback(new Error('最大人数必须大于最小人数'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        return {
            dialogVisible: false,
            logType: '',
            formData: {
                time: null,
                name: '',
                type: 'register',
                rewardType: 1,
                rewardNum: null,
                rewardPrice: null,
                giftConditionType: 1,
                description: '',
                ladderEnabled: false,
                ladderMin: '',
                ladderMan: '',
                ladderRewardType: 1,
                ladderRewardNum: '',
                ladderRewardPrice: '',
                rules: [{ queryType: 1, queryConditionType: 1, rewardType: 1, rewardNum: '', rewardPrice: '' }],
                posterUrls: '',
                note: ''
            },
            time: '',
            typeList: [{ label: '注册有礼', value: 'register' }, { label: '邀请有礼', value: 'brokerage' }, { label: '查询有礼', value: 'query' }],
            sendTypeList: [{ label: '查询次数', value: 1 }, { label: '现金红包', value: 2 }, { label: '查询次数+微信零钱', value: 3 }],
            tlList: [{ label: '注册', value: 1 }, { label: '税务查询', value: 2 }, { label: '推广邀请', value: 3 }],
            searchTypeList: [{ label: '首次查询', value: 1 }, { label: '重复查询', value: 2 }],
            queryConditionTypeList: [{ label: '近3年有开票纳税记录', value: 1 }, { label: '近3年无开票纳税记录', value: 2 }],

            // 校验规则
            rules: {
                name: [
                    { required: true, message: '请输入活动标题', trigger: 'blur' },
                    { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择活动类型', trigger: 'change' }
                ],
                ladderMin: [
                    { required: true, message: '请输入最小人数', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' }
                ],
                ladderMan: [
                    { required: true, message: '请输入最大人数', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' },
                    { validator: validateLadderRange, trigger: 'blur' }
                ],
                ladderRewardType: [
                    { required: true, message: '请选择阶梯奖励类型', trigger: 'change' }
                ],
                ladderRewardNum: [
                    { required: true, message: '请输入可查次数', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' }
                ],
                ladderRewardPrice: [
                    { required: true, message: '请输入奖励金额', trigger: 'blur' },
                    { validator: validateMoney, trigger: 'blur' }
                ],
                rewardType: [
                    { required: true, message: '请选择发送类型', trigger: 'change' }
                ],
                rewardNum: [
                    { required: true, message: '请输入可查次数', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' }
                ],
                rewardPrice: [
                    { required: true, message: '请输入奖励金额', trigger: 'blur' },
                    { validator: validateMoney, trigger: 'blur' }
                ],
                giftConditionType: [
                    { required: true, message: '请选择奖励发放条件', trigger: 'change' }
                ],
                description: [
                    { required: true, message: '请输入活动奖励规则', trigger: 'blur' }
                ],
                queryType: [
                    { required: true, message: '请选择查询类型', trigger: 'change' }
                ],
                queryConditionType: [
                    { required: true, message: '请选择查询条件', trigger: 'change' }
                ],
                rewardType: [
                    { required: true, message: '请选择奖励类型', trigger: 'change' }
                ],
                time: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
            }
        }
    },
    methods: {
        uploadSucces() { },
        addRule() {
            this.formData.rules.push({ queryType: 1, queryConditionType: 1, rewardType: 1, rewardNum: '', rewardPrice: '' })
        },

        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submit();
                } else {
                    this.$message.error('请检查表单填写是否正确');
                    return false;
                }
            });
        },

        submit() {
            let obj = Object.assign({}, this.formData);
            obj.startTime = this.formData.time[0];
            obj.endTime = this.formData.time[1];
            delete obj.time;
            obj.posterUrls = obj.posterUrls && obj.posterUrls.split(',')
            obj.ladderRewardPrice = obj.ladderRewardPrice && Number(obj.ladderRewardPrice) * 100
            obj.rewardPrice = obj.rewardPrice && Number(obj.rewardPrice) * 100
            obj.rules = obj.rules && obj.rules.map(item => {
                if (item.rewardType == 1) {
                    item.rewardPrice = ''
                }
                if (item.rewardType == 2) {
                    item.rewardNum = ''
                }
                 item.rewardPrice = item.rewardPrice && Number(item.rewardPrice) * 100
                return item
            })
            if (this.logType == 'create') {
                addActivity(obj).then(res => {
                    this.$message.success('添加成功');
                    this.handleClose();
                    this.$emit('getList');
                });
            } else {
                updateActivity(obj).then(res => {
                    this.$message.success('修改成功');
                    this.handleClose();
                    this.$emit('getList');
                });
            }
        },

        handleClose() {
            this.dialogVisible = false
        },

        open(type, val = {}) {
            this.formData = {
                time: null,
                name: '',
                type: 'register',
                rewardType: 1,
                rewardNum: null,
                rewardPrice: null,
                giftConditionType: 1,
                description: '',
                ladderEnabled: false,
                ladderMin: '',
                ladderMan: '',
                ladderRewardType: 1,
                ladderRewardNum: '',
                ladderRewardPrice: '',
                rules: [{ queryType: 1, queryConditionType: 1, rewardType: 1, rewardNum: '', rewardPrice: '' }]
            }
            this.$nextTick(() => {
                this.$refs.tinymce.setContent('');
            })
            if (type == 'update') {
                activityInfo(val.id).then(res => {
                    let obj = res.data;
                    obj.ladderRewardPrice = obj.ladderRewardPrice && Number(obj.ladderRewardPrice) / 100
                    obj.rewardPrice = obj.rewardPrice && Number(obj.rewardPrice / 100)
                    obj.rules.forEach(item => {

                        item.rewardPrice = (item.rewardPrice) / 100
                    })
                    console.log(obj.rules);
                    obj.time = [obj.startTime, obj.endTime];
                    obj.posterUrls = obj.posterUrls && obj.posterUrls.join(',')
                    this.$refs.tinymce.setContent(obj.description);
                    this.formData = obj;
                });
            }
            this.logType = type
            this.dialogVisible = true
        }
    },
}
</script>

<style></style>